<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 系统加密方法
 * @param $value
 * @return string
 */
function qa_encrtyp($value){
    $data = openssl_encrypt($value,'DES-ECB',config('AUTH.ENCRTYP_CODE'),0);
    return base64_encode($data);
}

/**
 * 系统解密方法
 * @param $value
 * @return string
 */
function qa_decrtyp($value){
    $data = base64_decode($value);
    return openssl_decrypt($data,'DES-ECB',config('AUTH.ENCRTYP_CODE'),0);
}

function get_user_id(){
    return session('u_id');
}

function left_nav(){
    $user_id = get_user_id();
    $node = [];
    $where['status'] = 1;
    $where['is_menu'] = 1;

    if ($user_id == 1){//超级管理员账号，拥有系统所有权限
        $node = db('rule')->where($where)->order('sort','asc')->select();
    }else{//其它账号
        $user_role = db('user_role')->where('user_id',$user_id)->column('role_id');
        if (!empty($user_role)){
            $role_node = db('role_rule')->where('role_id','in',$user_role)->column('rule_id');
            if (!empty($role_node)){
                $node = db('rule')
                    ->where('status',1)
                    ->where('is_menu',1)
                    ->where('id','in',$role_node)
                    ->order('sort','asc')
                    ->select();
            }
        }
    }
    $node = list_to_tree($node);
    echo get_tree_nav($node);
}

function get_tree_nav($nav_list,$level = 0){
    $html = "";
    $level++;
    if (is_array($nav_list)) {
        foreach ($nav_list as $val) {
            $node_name = $val['name'];
            $icon = !empty($val['icon']) ? $val['icon'] : "fa fa-star-o fa-fw";
            $node_id = $val['id'];

            $html .= "<li>\r\n";
            if (isset($val['_child']) || $val['pid'] == 0){
                //有子级
                $html .= "<a href='javascript:;'>\r\n";
            }else{
                //无子级 叶子节点
                $url = '';
                $url = '"' . url($val['rule'],['node'=>$node_id]) . '"';
                $html .= "<a onclick='xadmin.add_tab(\"$node_name\",$url)'>\r\n";
                cookie('current_action',$node_id);

            }
            $html .= "<i class='" . $icon . "' lay-tip='" . $node_name . "'></i>\r\n";
            $html .= "<cite>" . $node_name . "</cite>\r\n";
            if (isset($val['_child'])) {
                $html .= "<i class='fa fa-chevron-right right-ico'></i>\r\n";
            }
            $html .= "</a>\r\n";
            if (isset($val['_child'])) {
                $html .= "<ul class='sub-menu'>\r\n";
                $html .= get_tree_nav($val['_child'], $level);
                $html .= "</ul>\r\n";
                $html .= "</li>\r\n";
            }

        }
    }
    return $html;
}

function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'pid', $child = '_child') {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用

        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string)$root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 判断当前父级下是否已存在该子级名称
 * @param $model 表名
 * @param $pid 父级id
 * @param $name 子级的名称
 * @param $id
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function son_repeat($model, $pid, $name, $id = ''){
    $where[] = ['name', '=', $name];
    $where[] = ['pid', '=', $pid];
    if (!empty($id)) {
        $where[] = ['id', '<>', $id];
    }
    $repeat = db($model)->where($where)->find();
    if ($repeat) {
        //已重复
        return true;
    } else {
        //未重复
        return false;
    }
}

/**
 * 转化为数据词典
 * @param $arr
 * @return array [key => value]
 */
function to_dict($arr){
    $new = [];
    foreach ($arr as $k => $v){
        $new[$v['id']] = $v['name'];
    }
    return $new;
}

/**
 * 写入系统操作日志
 * @param $content 日志内容
 * @param string $user_id 操作账号id
 */
function insert_system_log($content,$user_id = ''){
    if (empty($user_id)){
        $user_id = intval(get_user_id());
    }

    $log_data = [
        'user' => $user_id,
        'username' => cookie('u_name'),
        'name' => session('name'),
        'content' => $content,
        'create_time' => time()
    ];

    db('system_log')->insert($log_data);
}

//清理缓存函数
if (!function_exists('delete_dir_file'))
{
    /**
     * 循环删除目录和文件
     * @param string $dir_name
     * @return bool
     */
    function delete_dir_file($dir_name) {
        $result = false;
        if(is_dir($dir_name)){
            if ($handle = opendir($dir_name)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
                            delete_dir_file($dir_name . DIRECTORY_SEPARATOR . $item);
                        } else {
                            unlink($dir_name . DIRECTORY_SEPARATOR . $item);
                        }
                    }
                }
                closedir($handle);
                if (rmdir($dir_name)) {
                    $result = true;
                }
            }
        }
        return $result;
    }
}

/**
 * 获取客户端IP地址
 * @return mixed
 */
function real_ip(){
    $ip = '未知IP';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return is_ip($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : $ip;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return is_ip($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $ip;
    } else {
        return is_ip($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $ip;
    }
}

/**
 * 验证IP格式
 * @param $str
 * @return bool|false|int
 */
function is_ip($str){
    $ip = explode('.', $str);
    for ($i = 0; $i < count($ip); $i++) {
        if ($ip[$i] > 255) {
            return false;
        }
    }
    return preg_match('/^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$/', $str);
}

/**
 * 二维数组指定字段重新排序
 * @param array $array 原数组
 * @param string $field 排序字段
 * @param int $sort 排序方式 SORT_DESC:倒序 SORT_ASC:升序
 * @return mixed
 */
function tree_array_sort($array,$field,$sort = SORT_DESC){
    $edit = array_column($array,$field);
    array_multisort($edit,$sort,$array);

    return $array;
}

/**
 * 二维数组根据键名进行分组
 * @param $arr 源数组
 * @param $key 键名
 * @return array
 */
function array_group_by($arr, $key) {
    $grouped = array();
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }

    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $params = array_merge($value,array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by',$params);
        }
    }

    return $grouped;
}

/**
 * 用户名格式验证
 * 只能由英文与数字组成，长度为6-25
 * @param $username
 * @return false|int
 */
function username_check($username){
    return preg_match('/^[a-zA-Z0-9]{6,25}$/',$username) ? true : false;
}

/**
 * 密码格式是否正确
 * @param $pwd
 * @return bool
 */
function pwd_check($pwd){
    return preg_match('/[0-9a-zA-Z]{6,20}/',$pwd) ? true : false;
}

/**
 * 手机号码格式是否正确
 * @param $phone
 * @return false|int
 */
function is_phone($phone){
    return preg_match("/^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/",$phone) ? true : false;
}

/**
 * 电话号码格式是否正确
 * @param $mobile
 * @return false|int
 */
function is_mobile($mobile){
    return preg_match('/\d{3}-\d{8}|\d{4}-\d{7}/',$mobile) ? true : false;
}

/**
 * 邮箱格式是否正确
 * @param $email
 * @return bool
 */
function is_email($email){
    return preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/",$email) ? true : false;
}

/**
 * 身份证格式是否正确
 * @param $id_card
 * @return false|int
 */
function is_id_card($id_card){
    return preg_match("/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/",$id_card);
}

function is_post(){
    return request()->isPost() ? true : false;
}

/**
 * 获取系统设置值
 * @param $code
 * @return mixed
 */
function get_system_val($code){
    return db('system_config')->where('code',$code)->value('val');
}

function handle_list_link($module,$id,$seo_link){
    $link = empty($seo_link) ? url('index/' . $module . '/index',['id' => $id]) : url('index/' . $module . '/index',['id' => $seo_link]);

    return $link;
}

function handle_detail_link($module,$id,$seo_link){

    $link = empty($seo_link) ? url('index/' . $module . '/details',['id' => $id]) : url('index/' . $module . '/details',['id' => $seo_link]);

    return $link;
}